package com.demo.servlet.demo1208;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

//1.创建一个类 继承 HttpServlet
//2.重写方法 doGet doPost
//3.添加注解 配置映射URL
@WebServlet("/demo03.do")
public class Demo03Servlet extends HttpServlet {
    /**
     * @param request  由Tomcat封装 将浏览器发送来的所有请求数据 都封装在该对象中。以获取（get）为主
     * @param response 由Tomcat封装 将服务器即将发送给浏览器的响应数据 封装在该对象中。以设置为主
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //HttpServletRequest 获取参数的方法介绍
        //1.通过参数名 获取一个 value
        String username = request.getParameter("username");
        //doGet 中文请求乱码
        //1.先以ISO-8859-1 进行编码
        //2.以UTF-8 进行解码
        username = new String(username.getBytes("iso-8859-1"), "UTF-8");

        System.out.println("用户名 = " + username);

        String password = request.getParameter("password");
        System.out.println("密码 = " + password);

        //2.通过参数名 获取组个 value
        String[] hobbies = request.getParameterValues("hobby");
        System.out.println(Arrays.asList(hobbies));

        //3.获取请求参数集合
        Map<String, String[]> parameterMap = request.getParameterMap();
        //使用 entrySet 遍历请求参数集合
        Set<Map.Entry<String, String[]>> entries = parameterMap.entrySet();
        Iterator<Map.Entry<String, String[]>> iterator = entries.iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String[]> next = iterator.next();
            System.out.println("请求参数名称为：" + next.getKey());
            System.out.println("请求参数值为：" + Arrays.asList(next.getValue()));
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //POST 中文请求乱码解决
        request.setCharacterEncoding("UTF-8");
        doGet(request, response);
    }
}
